/**
 * 熵巡 - 企业级氚云OpenAPI数据管理平台
 * 开发归属 Alyr.net
 * 数据同步模块
 * 尊重劳动成果是一种美德
 */


let isSyncLoading = false;

// 页面加载后初始化
document.addEventListener('DOMContentLoaded', function() {
    // 监听TAB切换，切换到数据同步TAB时加载表单选择器
    const observer = new MutationObserver(function(mutations) {
        mutations.forEach(function(mutation) {
            if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
                const target = mutation.target;
                if (target.id === 'data-sync' && target.classList.contains('active')) {
                    loadSyncSchemaSelector();
                    if (!isSyncLoading) {
                        initSyncInterface();
                    }
                }
            }
        });
    });
    
    const dataSyncTab = document.getElementById('data-sync');
    if (dataSyncTab) {
        observer.observe(dataSyncTab, { attributes: true });
        // 如果已经是激活状态，立即加载
        if (dataSyncTab.classList.contains('active')) {
            setTimeout(() => {
                loadSyncSchemaSelector();
                initSyncInterface();
            }, 500);
        }
    }
});

// 加载表单选择器
function loadSyncSchemaSelector() {
    const select = document.getElementById('sync-schema-select');
    if (!select) {
        console.error('数据同步表单选择器元素未找到');
        return;
    }
    
    console.log('开始加载数据同步表单选择器');
    
    fetch('api/get_schemas.php')
        .then(response => {
            if (!response.ok) {
                throw new Error('HTTP ' + response.status);
            }
            return response.json();
        })
        .then(data => {
            if (data.success && data.schemas) {
                let html = '';
                data.schemas.forEach((schema, index) => {
                    const selected = index === 0 ? 'selected' : '';
                    html += `<option value="${schema.schema_key}" ${selected}>${schema.schema_name}</option>`;
                });
                if (data.schemas.length > 1) {
                    html += '<option value="all">全部表单</option>';
                }
                select.innerHTML = html;
                console.log('数据同步表单选择器加载成功，共', data.schemas.length, '个表单');
            } else {
                select.innerHTML = '<option value="default">默认表单</option>';
            }
        })
        .catch(error => {
            console.error('加载数据同步表单选择器失败:', error);
            select.innerHTML = '<option value="default">默认表单</option>';
        });
}

// 初始化同步界面
function initSyncInterface() {
    const syncSection = document.getElementById('data-sync');
    if (!syncSection) return;
    
    // 检查是否已经初始化
    if (syncSection.querySelector('.sync-panel')) return;
    
    const html = `
        <div class="sync-panel">
            <div class="sync-filters">
                <h4>过滤条件</h4>
                <div class="filter-container">
                    <label for="date-type">时间范围:</label>
                    <select id="date-type" onchange="toggleDateInputs()">
                        <option value="today">当日</option>
                        <option value="yesterday">昨日</option>
                        <option value="week">近七天</option>
                        <option value="month">近一月</option>
                        <option value="custom">自定义</option>
                    </select>
                    
                    <span id="custom-dates" style="display:none;">
                        <input type="date" id="start-date" value="${new Date().toISOString().split('T')[0]}">
                        <span>至</span>
                        <input type="date" id="end-date" value="${new Date().toISOString().split('T')[0]}">
                    </span>
                    
                    <label for="data-limit">显示条数:</label>
                    <select id="data-limit">
                        <option value="1000">1000 条</option>
                        <option value="5000">5000 条</option>
                        <option value="10000" selected>10000 条</option>
                        <option value="50000">50000 条</option>
                    </select>
                    
                    <label for="sort-order">排序方式:</label>
                    <select id="sort-order">
                        <option value="desc" selected>时间降序 (最新在前)</option>
                        <option value="asc">时间升序 (最旧在前)</option>
                    </select>
                    
                    <button id="sync-btn" class="btn btn-primary" onclick="startDataSync()">
                        <span id="sync-btn-text">开始同步</span>
                    </button>
                    <button class="btn btn-secondary" onclick="resetFilters()">
                        重置过滤
                    </button>
                </div>
            </div>
            
            <div id="sync-status" class="sync-status">
                请选择筛选条件，点击"开始同步"按钮开始同步...
            </div>
            
            <div id="sync-results" class="sync-results" style="display:none;">
                <!-- 同步结果将显示在这里 -->
            </div>
        </div>
    `;
    
    syncSection.innerHTML = syncSection.innerHTML.replace('<!-- 功能开发中 -->', html);
    console.log('数据同步界面初始化完成');
}

// 切换日期输入框显示
function toggleDateInputs() {
    const dateType = document.getElementById('date-type').value;
    const customDates = document.getElementById('custom-dates');
    
    if (dateType === 'custom') {
        customDates.style.display = 'flex';
    } else {
        customDates.style.display = 'none';
    }
}

// 重置过滤条件
function resetFilters() {
    document.getElementById('date-type').value = 'today';
    document.getElementById('data-limit').value = '10000';
    document.getElementById('sort-order').value = 'desc';
    document.getElementById('start-date').value = new Date().toISOString().split('T')[0];
    document.getElementById('end-date').value = new Date().toISOString().split('T')[0];
    toggleDateInputs();
    
    // 重置状态提示
    updateSyncStatus('请选择筛选条件，点击"开始同步"按钮开始同步...', '');
    
    // 清空同步结果
    const resultsDiv = document.getElementById('sync-results');
    if (resultsDiv) {
        resultsDiv.innerHTML = '';
        resultsDiv.style.display = 'none';
    }
}

// 获取过滤参数
function getFilterParams() {
    const dateType = document.getElementById('date-type').value;
    const dataLimit = document.getElementById('data-limit').value;
    const sortOrder = document.getElementById('sort-order').value;
    
    let startDate, endDate;
    
    switch (dateType) {
        case 'today':
            startDate = new Date().toISOString().split('T')[0];
            endDate = startDate;
            break;
        case 'yesterday':
            const yesterday = new Date();
            yesterday.setDate(yesterday.getDate() - 1);
            startDate = yesterday.toISOString().split('T')[0];
            endDate = startDate;
            break;
        case 'week':
            const weekAgo = new Date();
            weekAgo.setDate(weekAgo.getDate() - 7);
            startDate = weekAgo.toISOString().split('T')[0];
            endDate = new Date().toISOString().split('T')[0];
            break;
        case 'month':
            const monthAgo = new Date();
            monthAgo.setMonth(monthAgo.getMonth() - 1);
            startDate = monthAgo.toISOString().split('T')[0];
            endDate = new Date().toISOString().split('T')[0];
            break;
        case 'custom':
            startDate = document.getElementById('start-date').value;
            endDate = document.getElementById('end-date').value;
            break;
    }
    
    return {
        dateType: dateType,
        startDate: startDate,
        endDate: endDate,
        dataLimit: parseInt(dataLimit),
        sortOrder: sortOrder
    };
}

// 开始数据同步
function startDataSync() {
    if (isSyncLoading) return;
    
    // 获取选中的表单
    const schemaSelect = document.getElementById('sync-schema-select');
    if (!schemaSelect || !schemaSelect.value) {
        updateSyncStatus('请先选择表单', 'error');
        return;
    }
    const schemaKey = schemaSelect.value;
    
    // 获取过滤参数
    const filters = getFilterParams();
    
    console.log('开始数据同步...', { schema: schemaKey, ...filters });
    updateSyncStatus(`正在查询数据 (${filters.startDate} 至 ${filters.endDate})...`, 'loading');
    updateSyncButton(true);
    isSyncLoading = true;
    
    // 构建请求参数
    const params = new URLSearchParams({
        action: 'sync_data',
        schema: schemaKey,
        date_type: filters.dateType,
        start_date: filters.startDate,
        end_date: filters.endDate,
        data_limit: filters.dataLimit,
        sort_order: filters.sortOrder
    });
    
    fetch(`api/data_sync.php?${params.toString()}`, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/json',
        }
    })
    .then(response => {
        console.log('同步响应状态:', response.status);
        console.log('Content-Type:', response.headers.get('content-type'));
        
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        const contentType = response.headers.get('content-type');
        if (!contentType || !contentType.includes('application/json')) {
            console.warn('响应不是JSON格式:', contentType);
            throw new Error('服务器返回非 JSON 数据，可能出现错误');
        }
        
        return response.text();
    })
    .then(text => {
        console.log('同步原始响应:', text.substring(0, 200));
        
        // 检查是否是HTML错误页面
        if (text.trim().startsWith('<') || 
            text.includes('<html') || 
            text.includes('<br />') || 
            text.includes('<b>') ||
            text.includes('Fatal error') ||
            text.includes('Parse error')) {
            throw new Error('API返回HTML错误页面而非JSON数据，请检查服务器配置');
        }
        
        // 检查是否为空响应
        if (!text || text.trim() === '') {
            throw new Error('服务器返回空响应');
        }
        
        // 尝试解析JSON
        try {
            return JSON.parse(text);
        } catch (parseError) {
            console.error('JSON解析错误:', parseError.message);
            console.error('响应内容:', text);
            throw new Error(`JSON解析失败: ${parseError.message}，响应内容可能不是有效的JSON格式`);
        }
    })
    .then(data => {
        console.log('数据同步响应:', data);
        if (data.success) {
            displaySyncResults(data);
            updateSyncStatus(`数据同步完成，共 ${data.data_count} 条数据 (${data.sync_time})`, 'success');
        } else {
            updateSyncStatus('同步失败: ' + data.message, 'error');
            console.error('数据同步失败:', data);
        }
    })
    .catch(error => {
        updateSyncStatus('同步异常: ' + error.message, 'error');
        console.error('数据同步异常:', error);
    })
    .finally(() => {
        updateSyncButton(false);
        isSyncLoading = false;
    });
}



// 显示同步结果
function displaySyncResults(data) {
    const resultsDiv = document.getElementById('sync-results');
    if (!resultsDiv) return;
    
    let html = `
        <div class="sync-result-card">
            <h4>同步成功</h4>
            <div class="sync-info">
                <div class="info-item">
                    <span class="label">数据条数:</span>
                    <span class="value">${data.data_count} 条</span>
                </div>
                <div class="info-item">
                    <span class="label">文件大小:</span>
                    <span class="value">${data.file_size}</span>
                </div>
                <div class="info-item">
                    <span class="label">同步时间:</span>
                    <span class="value">${data.sync_time}</span>
                </div>
                <div class="info-item">
                    <span class="label">文件名称:</span>
                    <span class="value">${data.file_path}</span>
                </div>
            </div>
            <div class="sync-actions">
                <button class="btn btn-secondary" onclick="downloadSyncFile('${data.file_path}')">
                    下载文件
                </button>
            </div>
        </div>
    `;
    
    resultsDiv.innerHTML = html;
    resultsDiv.style.display = 'block';
}

// 下载同步文件
function downloadSyncFile(fileName) {
    const link = document.createElement('a');
    link.href = `sync_data/${fileName}`;
    link.download = fileName;
    link.target = '_blank';
    
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    
    // 显示下载提示
    updateSyncStatus(`正在下载文件: ${fileName}`, 'success');
}

// 更新同步状态显示
function updateSyncStatus(message, type) {
    const statusElement = document.getElementById('sync-status');
    if (statusElement) {
        statusElement.textContent = message;
        statusElement.className = 'sync-status ' + type;
        statusElement.style.display = 'block';
        console.log('同步状态更新:', message, type);
    }
}

// 更新同步按钮状态
function updateSyncButton(loading) {
    const btn = document.getElementById('sync-btn');
    const btnText = document.getElementById('sync-btn-text');
    
    if (btn && btnText) {
        if (loading) {
            btn.disabled = true;
            btn.classList.add('loading');
            btnText.textContent = '同步中...';
        } else {
            btn.disabled = false;
            btn.classList.remove('loading');
            btnText.textContent = '开始同步';
        }
    }
}